;; e1.18

#|
this is a variation of e1.17 implementing concepts learned in e1.16: a  procedure with logarithmic time/space requirement that unfolds in an iterative process and solves e1.17
|#

(define (mult-it a b i)
    (define (halve   x) (/ x 2))
    (define (double  x) (* x 2))
    (define (is-even x) (= (remainder x 2) 0))
    (cond ((= b 1)
            (+ a i))
          ((is-even b)
            (mult-it (double a) (halve b) i))
          (else
            (mult-it a (- b 1) (+ i a)))))
(define (mult a b) (mult-it a b 0))

; try to prove tail recursion
(mult 20 40)
(mult-it 20 40 0)
(mult-it 40 20 0)
(mult-it 80 10 0)
(mult-it 160 5 0)
(mult-it 160 4 160)
(mult-it 320 2 160)
(mult-it 640 1 160)
; nothing fancy here, this is really just a copy of e1.16 and e1.17
